<?php


namespace app\index\controller;

use think\Db;

/**
 * 数据库事物
 * Class DbTransactionTest
 * @package app\index\controller
 */
class DbTransactionTest
{
    /**
     * 事物
     */
    public function transaction_test()
    {
        $res = Db::transaction(function () {
            return Db::table('t_order')
                ->data(['user_id' => 10000026, 'order_name' => '草莓', 'price' => 20])
                ->insert();
        });
        dump($res);
    }

    /**
     * 手动事物
     */
    public function transaction_test2()
    {
        // 开启事务
        Db::startTrans();
        try {
            $res = Db::table('t_order')
                ->data(['user_id' => 10000026, 'order_name' => '车厘子', 'price' => 50])
                ->insert();
            // 提交事务
            Db::commit();
            return json(['msg' => '新增成功', 'data' => $res]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json('新增失败');
        }
    }

}